package org.threebitsoftware.tbb.Contact_GUI;
import javax.swing.JOptionPane;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import com.swtdesigner.SWTResourceManager;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.custom.CCombo;
import org.threebitsoftware.dao.generated.AppExternalservices;
import org.threebitsoftware.tbb.engine.EngineUtil;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.events.VerifyEvent;

public class Sync_WebService_GUI extends Dialog {
	
	private static Logger logger = Logger.getLogger(Sync_WebService_GUI.class);
	
	private Text usernameText_;
	private Text passwordText_;
	private Shell shell;
	private Object result_;
	private static int appUserID_ = -1;
	Label lblUsername ;
	Label lblPassword ;
	Label lblSerivce ;
	CCombo serviceCombox_;
	CCombo syncCombox_;
	Button btnRemeberMe;
	private Button btnSync_;
	boolean rememberClicked = false;
	private String emailToTest="";
	
	/**
	 * Create the shell.
	 * 
	 * @param display
	 */
	public Sync_WebService_GUI(Shell parent, int style, int appUserID) {
		super(parent, style);
		setText("SWT Dialog");
		appUserID_ = appUserID;

	}
	
	
	/**
	 * Launch the application.
	 * 
	 * @param args
	 */
	public Object open() {
		try {
			createContents();
			shell.open();
			shell.layout();

			Display display = Display.getDefault();
			while (!shell.isDisposed()) {
				if (!display.readAndDispatch()) {
					display.sleep();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result_;
	}



	/**
	 * Create contents of the shell.
	 */
	protected void createContents() {

		shell = new Shell(getParent(), SWT.DIALOG_TRIM
				| SWT.APPLICATION_MODAL);
		shell.setBackground(SWTResourceManager
				.getColor(SWT.COLOR_WIDGET_BACKGROUND));
		shell.setSize(356, 286);
		shell.setText("TBB Webservice");

		{
			lblUsername = new Label(shell, SWT.NONE);
			lblUsername.setFont(SWTResourceManager.getFont("Tahoma", 10,
					SWT.NORMAL));
			lblUsername.setBounds(10, 49, 86, 20);
			lblUsername.setText("Username");
		}
		{
			usernameText_ = new Text(shell, SWT.BORDER);
			usernameText_.addVerifyListener(new VerifyListener() {
				public void verifyText(VerifyEvent arg0) {
					
					emailToTest = emailToTest + arg0.character;
					
				}
			});
			usernameText_.setBounds(102, 48, 141, 21);
		}
		{
			lblPassword = new Label(shell, SWT.NONE);
			lblPassword.setFont(SWTResourceManager.getFont("Tahoma", 10,
					SWT.NORMAL));
			lblPassword.setBounds(10, 76, 86, 20);
			lblPassword.setText("Password");
		}
		{
			passwordText_ = new Text(shell, SWT.BORDER|SWT.SINGLE|SWT.PASSWORD);
			passwordText_.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseDown(MouseEvent e) {
					
					boolean isEmailValid = FieldValidation.RuleEmailAt(emailToTest);
					
					if (isEmailValid){
						logger.debug(usernameText_.getText() + " is valid");
						System.out.println("Searching if " + usernameText_.getText() + " is remembered.");
						AppExternalservices userServiceAccountInfo = getRemeberedUserCredentials(usernameText_.getText());
						
						if (userServiceAccountInfo!=null){//user password is stored in the system.
							passwordText_.setText(userServiceAccountInfo.getSPassword());	
						} 	
					} else if (!isEmailValid){
						logger.debug(usernameText_.getText()+ " not is valid");
						JOptionPane.showMessageDialog(null,"Invalid Email. Please check you email.",
								null, 
								JOptionPane.NO_OPTION);
//						usernameText_.setText("");
					}
					
				}
			});
			passwordText_.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					System.out.println("Searching if " + usernameText_.getText() + " is remembered.");
					AppExternalservices userServiceAccountInfo = getRemeberedUserCredentials(usernameText_.getText());
					
					if (userServiceAccountInfo!=null){//user password is stored in the system.
						passwordText_.setText(userServiceAccountInfo.getSPassword());	
					}
					
				}
			});
			passwordText_.setBounds(102, 75, 141, 21);
		}
		{
			lblSerivce = new Label(shell, SWT.NONE);
			lblSerivce.setFont(SWTResourceManager.getFont("Tahoma", 10,
					SWT.NORMAL));
			lblSerivce.setBounds(10, 23, 85, 20);
			lblSerivce.setText("Serivce");
		}
		
		{//Sync Button---------------------------------------->
			btnSync_ = new Button(shell, SWT.NONE);
			
			//Sync should remaining disable until a Sync Option is selected from the Drop Down.
			btnSync_.setEnabled(false);
			btnSync_.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					System.out.println("Syncing the login for username " + usernameText_.getText());
				
				
					//Just log the user to google account without remembering
					if (!rememberClicked){
					//login to user's google account. But do not remember password.
					boolean loginStatus = EngineUtil.useWebServiceHandler("org.threebitsoftware.tbb.module.webservice.Gcontacts", usernameText_.getText(), passwordText_.getText(), syncCombox_.getSelectionIndex());
				
//					if (loginStatus==false){
//						JOptionPane.showMessageDialog(null,"Invalid Credentials.",
//								null, 
//								JOptionPane.ERROR_MESSAGE);
//					}
					
					}
					//Remember the user and then log in to google account. 
					else if (rememberClicked && btnRemeberMe.getSelection()){
						
						AppExternalservices newAppUserInfo = new AppExternalservices();
						newAppUserInfo.setIdAppUser(appUserID_);
						newAppUserInfo.setSUsername(usernameText_.getText());
						newAppUserInfo.setSPassword(passwordText_.getText());
						
						//id_app_module= 1 which is the org.threebitsoftware.tbb.module.webservice.Gcontacts
						newAppUserInfo.setIdAppModule(1);
						
						//Remember this user by adding him to a table. 
						EngineUtil.setWebServiceUserAccountInfo(newAppUserInfo);
						
						//logging user to google.
						EngineUtil.useWebServiceHandler("org.threebitsoftware.tbb.module.webservice.Gcontacts", usernameText_.getText(), passwordText_.getText(), syncCombox_.getSelectionIndex());
					}
					shell.close();
				}
			});
			btnSync_.setBounds(204, 180, 68, 23);
			btnSync_.setText("Sync");
			
		}
		
		{//Cancel Button------------------------------------->
			Button btnCancel_ = new Button(shell, SWT.NONE);
			btnCancel_.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					System.out.println("Resetting the form");
					resetForms(usernameText_);
					resetForms(passwordText_);
					resetForms(btnRemeberMe);
					resetForms(serviceCombox_);
					resetForms(syncCombox_);
					
					shell.close();
				}
			});
			btnCancel_.setBounds(116, 180, 68, 23);
			btnCancel_.setText("Cancel");
		}
		
		{//Edit Button------------------------------->
			Button btnEdit_ = new Button(shell, SWT.NONE);
			btnEdit_.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					
					System.out.println("Editing Users account Info for username " + usernameText_.getText());
					AppExternalservices appUserInfo = getRemeberedUserCredentials(usernameText_.getText());
					
					appUserInfo.setSUsername(usernameText_.getText());
					appUserInfo.setSPassword(passwordText_.getText());
					
					//appModuleID =1 is org.threebitsoftware.tbb.module.webservice.Gcontacts
					appUserInfo.setIdAppModule(1);
					setRemeberedUserCredentials(appUserInfo);
					
					shell.close();
				}
			});
			btnEdit_.setBounds(27, 180, 68, 23);
			btnEdit_.setText("Edit");
		}
		{
			btnRemeberMe = new Button(shell, SWT.CHECK);
			btnRemeberMe.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					System.out.println("User cliked Remeber Me");
					rememberClicked = true;
				}
			});
			
			btnRemeberMe.setFont(SWTResourceManager.getFont("Tahoma", 10,
					SWT.NORMAL));
			btnRemeberMe.setBounds(102, 150, 113, 16);
			btnRemeberMe.setSelection(false);
			btnRemeberMe.setText("Remember Me");
		}
		{
			serviceCombox_ = new CCombo(shell, SWT.BORDER);
			serviceCombox_.setEditable(false);
			serviceCombox_.setItems(new String[] { "Google" });
			serviceCombox_.setBounds(102, 22, 86, 20);
			serviceCombox_.select(0);
		}
		{
			syncCombox_ = new CCombo(shell, SWT.BORDER);
			syncCombox_.setEditable(false);
			syncCombox_.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					System.out.println("Sync options choice: " + syncCombox_.getText());
					btnSync_.setEnabled(true);
				}
			});
			syncCombox_.setListVisible(true);
			syncCombox_.setItems(new String[] { "Up", "Down", "Both" });
			syncCombox_.setBounds(102, 124, 113, 20);
			syncCombox_.select(0);
		}
		{
			Label lblSyncChoices = new Label(shell, SWT.NONE);
			lblSyncChoices.setFont(SWTResourceManager.getFont("Tahoma", 10,
					SWT.NORMAL));
			lblSyncChoices.setBounds(10, 124, 85, 21);
			lblSyncChoices.setText("Sync Choices");
		}

	}


public void resetForms (Control controlToBeReset){

	if (controlToBeReset instanceof Text){
	Text usernamPwdtextBox = (Text) controlToBeReset;
	System.out.println("Resetting Textbox: " + usernamPwdtextBox.getText());
	usernamPwdtextBox.setText("");
	} 
	
	else if (controlToBeReset instanceof CCombo){
		CCombo resetDropDown = (CCombo) controlToBeReset;
		System.out.println("Resetting DropDown: " + resetDropDown.getText());
		resetDropDown.select(0);
	} else if (controlToBeReset instanceof Button){
		Button resetCheckBox = (Button) controlToBeReset;
		System.out.println("Resetting CheckBox: " + resetCheckBox.getText());
		resetCheckBox.setSelection(false);
	}
	
	
}


private AppExternalservices getRemeberedUserCredentials(String appUsername){
	
	//Call database to get the User credentials to check if he is remembered user or not. 
	AppExternalservices  userWebServiceAccountInfo = EngineUtil.getWebServiceUserAccountInfo(appUsername);
	
	if (userWebServiceAccountInfo!=null){
		// set usernameText_
		usernameText_.setText(userWebServiceAccountInfo.getSUsername());
		passwordText_.setText(userWebServiceAccountInfo.getSPassword());
		//set passwordText_
		btnRemeberMe.setSelection(true);

	} else if (userWebServiceAccountInfo==null){
//		usernameText_.setText("");
		passwordText_.setText("");
		
	}
	return userWebServiceAccountInfo;
	
}


//Update the DB with new user account Info for the remembered user. 
private void setRemeberedUserCredentials(AppExternalservices updatedAppUserInfo){
	System.out.println("Updating user account.");
	EngineUtil.setWebServiceUserAccountInfo(updatedAppUserInfo);
}
}
